<?php

require_once PHP_UI_PATH . DS . 'Dependency.php';

abstract class DependencyManager implements Constraint {

    private $dependencies = array();

    public abstract function getEvent();

    public function getDependencies() {
        return $this->dependencies;
    }

    public function addDependency(Dependency $dependency) {
        $this->dependencies[] = $dependency;
    }

    protected abstract function getManagerClass();

    function render() {
        $render = "
            function {$this->getManagerClass()}(){
                this.dependencies = [];
                this.addDependency = function(dependent, independent){
                    if(!this.dependencies['_' + independent]){
                        this.dependencies['_' + independent] = [];
                    }
                    this.dependencies['_' + independent].push({dependent:'_' + dependent, independent:'_' + independent});
                    $('#_' + independent).addClass('{$this->getConstraintClass()}');
                }
                this.event = '{$this->getEvent()}';
                this.callback = {$this->renderCallback()};

                this.eventManager = function(event){
                    var _this = event.data.{$this->getManagerClass()};
                    var independent = this.id;
                    _this.callback(independent, _this.dependencies[independent]);
                }
            }
            var _{$this->getManagerClass()} = new {$this->getManagerClass()}();
            ";
        foreach ($this->dependencies as $dependency) {
            $render .= "_{$this->getManagerClass()}.addDependency({$dependency->getDependentControl()}, {$dependency->getIndependentControl()});";
        }

        $render .= "$('.{$this->getConstraintClass()}').bind('{$this->getEvent()}', {{$this->getManagerClass()}:_{$this->getManagerClass()}}, _{$this->getManagerClass()}.eventManager)";

        return $render;
    }

    abstract function renderCallback();
}

?>
